package com.vincce.fitness.core.base;

import com.vincce.fitness.entity.Admin;
import com.vincce.fitness.entity.Role;
import com.vincce.fitness.mappers.mgt.AdminMapper;
import com.vincce.fitness.mappers.mgt.RoleMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 * User: henry
 * Date: 8/7/13
 * Time: 2:23 PM
 * To change this template use File | Settings | File Templates.
 */
@Repository
public class AuthRealm extends AuthorizingRealm {

	@Resource
	private AdminMapper adminMapper;
	@Resource
	private RoleMapper roleMapper;



	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		Admin admin = (Admin) principalCollection.fromRealm(getName()).iterator().next();
		admin.setRoleList(roleMapper.findRoleByAdminId(admin.getId()));
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		for (Role role : admin.getRoleList()) {
			//基于Role的权限信息
			info.addRole(role.getName());
		}
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
		Admin admin = adminMapper.findAdminByName(upToken.getUsername());
		if (admin == null) {
			throw new UnknownAccountException("No account found for user [" + upToken.getUsername() + "]");
		} else {
			if (admin.getStatus().equals(2)) {
				throw new DisabledAccountException();
			}
		}

		return new SimpleAuthenticationInfo(admin, admin.getPassword(), getName());
	}


	public void setAdminMapper(AdminMapper adminMapper) {
		this.adminMapper = adminMapper;
	}

	public void setRoleMapper(RoleMapper roleMapper) {
		this.roleMapper = roleMapper;
	}
}
